package com.wing.sell.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.res.model.entity.ReceiptRecord;
import com.wing.res.model.entity.ReceiptRecordDetail;
import com.wing.res.service.ReceiptRecordDetailService;
import com.wing.res.service.ReceiptRecordService;
import com.wing.sell.dao.DeliveryPlanDao;
import com.wing.sell.dao.DeliveryRecordDao;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.DeliveryRecordForm;
import com.wing.sell.model.response.DeliveryRecordVO;
import com.wing.sell.service.*;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 交付记录表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class DeliveryRecordServiceImpl extends ServiceImpl<DeliveryRecordDao, DeliveryRecord> implements DeliveryRecordService {
    @Autowired
    private DeliveryPlanDao deliveryPlanDao;
    @Autowired
    private DeliveryRecordDetailService deliveryRecordDetailService;

    @Autowired
    private FinishedOrderDetailService finishedOrderDetailService;
    @Autowired
    private FinishedOrderService finishedOrderService;

    @Autowired
    private ReceiptRecordService receiptRecordService;

    @Autowired
    private ReceiptRecordDetailService receiptRecordDetailService;

    @Autowired
    private OrderProService orderProService;

    @Autowired
    private OrderService orderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(DeliveryRecordForm deliveryRecordForm) {
        //校验
        DeliveryRecord deliveryRecord = new DeliveryRecord();
        //交付记录编号
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        //getDayMaxNo
        String today = format.format(new Date());
        Integer maxCode = deliveryPlanDao.getDayMaxNo("sel_delivery_record");
        String maxNo = CodeUtil.getCode(maxCode);
        String code = "JL"+today + maxNo;
        CopyOptions copyOptions = CopyOptions.create().setEditable(DeliveryRecord.class).setIgnoreError(true).setIgnoreNullValue(true);
        BeanUtil.copyProperties(deliveryRecordForm, deliveryRecord, copyOptions);
        deliveryRecord.setRecordCode(code);
        deliveryRecord.setNo(Integer.valueOf(maxNo));
        deliveryRecord.setDay(Integer.valueOf(today));
        deliveryRecord.setSaleOrderCode(deliveryRecordForm.getSaleOrderCode());
        int recordResult = baseMapper.insert(deliveryRecord);
        if (recordResult == 0) {
            return 0;
        }
        //交付记录id
        Long recordID = deliveryRecord.getId();
        ReceiptRecord receiptRecord = ReceiptRecord.builder()
                .auditPerson(JwtUtils.getLoginUserId())
                .auditPersonName(JwtUtils.getLoginUsername())
                //出库已审核
                .auditResult("2")
                .creator(JwtUtils.getLoginUserId())
                .createTime(new Date())
                .creatorName(JwtUtils.getLoginUsername())
                .inventoryTypeId(deliveryRecordForm.getTypeId())
                //放入交付记录id
                .workOrderId(deliveryRecord.getId())
                .warehouseType(deliveryRecordForm.getWarehouseTypeId())
                .receiptWarehouse(deliveryRecordForm.getWarehouseId())
                .build();
        String taskNo = UniqueIdGeneratorUtil.generateUniqueId("LL", "yyyyMMdd", 1000, 9999);
        receiptRecord.setCode(taskNo);
        //待审核
        receiptRecord.setStatus(2);
        //如果是成品销售
        if (deliveryRecordForm.getTypeCode().equals(ProductEnum.outTypeEmum.CPC.getCode())) {
            //添加出库任务
            receiptRecord.setRemark("成品发货物流记录自动生成");
            this.receiptRecordService.save(receiptRecord);
            //成品销售逻辑
            if (CollectionUtil.isNotEmpty(deliveryRecordForm.getDeliveryRecordDetails())) {
                for (DeliveryRecordDetail deliveryRecordDetail : deliveryRecordForm.getDeliveryRecordDetails()) {
                    deliveryRecordDetail.setSkuId(deliveryRecordDetail.getProductDetailId());
                    deliveryRecordDetail.setUnitId(deliveryRecordDetail.getMainUnitId());
                    deliveryRecordDetail.setUnitName(deliveryRecordDetail.getMainUnitName());
                    deliveryRecordDetail.setProductName(deliveryRecordDetail.getSkuName());
                    deliveryRecordDetail.setSubtotalAmount(deliveryRecordDetail.getSubtotalAmount());
                    Long selRemainQuality = deliveryRecordDetail.getSelRemainQuality();
                    //上次剩余
                    Long lastQuality = null;
                    if (null != selRemainQuality && !selRemainQuality.equals(0L)) {
                        //得到此次剩余
                        lastQuality = selRemainQuality - deliveryRecordDetail.getShipmentQty();
                        deliveryRecordDetail.setSurplus(lastQuality);
                    }
                    deliveryRecordDetail.setDeliveryRecordId(recordID);
                    //交付情况:0-未交付，1-交付有剩余，2-交付完成
                    if (null != lastQuality && lastQuality > 0L) {
                        deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.JFYSY.getCode());
                    } else if (null != lastQuality && lastQuality == 0L) {
                        deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.JFWC.getCode());
                    } else {
                        deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.WJF.getCode());
                    }
                    //保存记录
                    this.deliveryRecordDetailService.save(deliveryRecordDetail);
                    //修改对应订单状态 以及剩余库存
                    QueryWrapper<FinishedOrderDetail> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("id", deliveryRecordDetail.getOrderDetailId());
                    queryWrapper.eq("finished_id", deliveryRecord.getSaleOrderId());
                    FinishedOrderDetail one = this.finishedOrderDetailService.getOne(queryWrapper);
                    one.setSelRemainQuality(lastQuality);
                    one.setUpdateTime(LocalDateTime.now());
                    one.setModifier(JwtUtils.getLoginUserId());
                    one.setModifierName(JwtUtils.getLoginUsername());
                    this.finishedOrderDetailService.updateById(one);

                    ReceiptRecordDetail receiptRecordDetail = new ReceiptRecordDetail();
                    receiptRecordDetail.setReceiptRecordId(receiptRecord.getId());
                    receiptRecordDetail.setProductDetailId(deliveryRecordDetail.getProductDetailId());
                    receiptRecordDetail.setReceiptNum(new BigDecimal(deliveryRecordDetail.getShipmentQty()));
                    receiptRecordDetail.setRemark("成品发货物流记录自动生成");
                    receiptRecordDetail.setCreateTime(new Date());
                    this.receiptRecordDetailService.save(receiptRecordDetail);
                }
            }
        }
        //生产订单出库
        else if(deliveryRecordForm.getTypeCode().equals(ProductEnum.outTypeEmum.SCDC.getCode())){
            //添加出库任务
            receiptRecord.setRemark("生产发货物流记录自动生成");
            this.receiptRecordService.save(receiptRecord);
            //生产销售逻辑
            if (CollectionUtil.isNotEmpty(deliveryRecordForm.getDeliveryRecordDetails())) {
                for (DeliveryRecordDetail deliveryRecordDetail : deliveryRecordForm.getDeliveryRecordDetails()) {
                    deliveryRecordDetail.setSkuId(deliveryRecordDetail.getProductDetailId());
                    deliveryRecordDetail.setUnitId(deliveryRecordDetail.getMainUnitId());
                    deliveryRecordDetail.setUnitName(deliveryRecordDetail.getMainUnitName());
                    deliveryRecordDetail.setProductName(deliveryRecordDetail.getSkuName());
                    deliveryRecordDetail.setSubtotalAmount(deliveryRecordDetail.getSubtotalAmount());
                    Long selRemainQuality = deliveryRecordDetail.getSelRemainQuality();
                    //上次剩余
                    Long lastQuality = null;
                    if (null != selRemainQuality && !selRemainQuality.equals(0L)) {
                        //得到此次剩余
                        lastQuality = selRemainQuality - deliveryRecordDetail.getShipmentQty();
                        deliveryRecordDetail.setSurplus(lastQuality);
                    }
                    deliveryRecordDetail.setDeliveryRecordId(recordID);
                    //交付情况:0-未交付，1-交付有剩余，2-交付完成
                    if (null != lastQuality && lastQuality > 0L) {
                        deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.JFYSY.getCode());
                    } else if (null != lastQuality && lastQuality == 0L) {
                        deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.JFWC.getCode());
                    } else {
                        deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.WJF.getCode());
                    }
                    //保存记录
                    this.deliveryRecordDetailService.save(deliveryRecordDetail);
                    //修改对应订单状态 以及剩余库存
                    QueryWrapper<OrderPro> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("id", deliveryRecordDetail.getOrderDetailId());
                    queryWrapper.eq("order_id", deliveryRecord.getSaleOrderId());
                    OrderPro serviceOne = this.orderProService.getOne(queryWrapper);
                    serviceOne.setSelRemainQuality(lastQuality);
                    serviceOne.setUpdateTime(LocalDateTime.now());
                    serviceOne.setModifier(JwtUtils.getLoginUserId());
                    serviceOne.setModifierName(JwtUtils.getLoginUsername());
                    this.orderProService.updateById(serviceOne);

                    ReceiptRecordDetail receiptRecordDetail = new ReceiptRecordDetail();
                    receiptRecordDetail.setReceiptRecordId(receiptRecord.getId());
                    receiptRecordDetail.setProductDetailId(deliveryRecordDetail.getProductDetailId());
                    receiptRecordDetail.setReceiptNum(new BigDecimal(deliveryRecordDetail.getShipmentQty()));
                    receiptRecordDetail.setRemark("生产发货物流记录自动生成");
                    receiptRecordDetail.setCreateTime(new Date());
                    this.receiptRecordDetailService.save(receiptRecordDetail);
                }
            }
        }
        return 1;
    }

    @Override
    public List<DeliveryRecordVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<DeliveryRecordVO> pageList4app(Page page, Map<String, Object> params) {
        List<DeliveryRecordVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public DeliveryRecordVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }


    @Override
    public Page<DeliveryRecordVO> pageDeliveryRecordList(Page page, Map<String, Object> params) {
        List<DeliveryRecordVO> list = baseMapper.deliveryRecordList(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<DeliveryRecordVO> saleOrderList(Map<String, Object> params) {
        return baseMapper.saleOrderList(params);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public DeliveryRecordForm getDetailBy(Long id) {
        //1. 查询交付记录详情
        DeliveryRecordForm detailBy = baseMapper.getDetailBy(id);

        Long saleOrderId = detailBy.getSaleOrderId();
        //成品销售 查询成品销售表
        if (detailBy.getTypeCode().equals(ProductEnum.outTypeEmum.CPC.getCode())){
            FinishedOrder orderServiceById = this.finishedOrderService.getById(saleOrderId);
            if (ObjectUtil.isNotEmpty(orderServiceById)){
                detailBy.setOrderPlanOnTime(orderServiceById.getPlanOnTime());
                detailBy.setOrderCreateTime(orderServiceById.getCreateTime());
                detailBy.setSaleOrderCode(orderServiceById.getSelCode());
            }
        }else if((detailBy.getTypeCode().equals(ProductEnum.outTypeEmum.SCDC.getCode()))){
            Order byId = orderService.getById(saleOrderId);
            if (ObjectUtil.isNotEmpty(byId)){
                detailBy.setOrderPlanOnTime(byId.getDeliveryTime());
                detailBy.setOrderCreateTime(byId.getCreateTime());
                detailBy.setSaleOrderCode(byId.getCode());

            }
        }
        //查询出出入库code

        //2. 查询交付记录明细
        QueryWrapper<DeliveryRecordDetail> deliveryRecordDetailQueryWrapper = new QueryWrapper<>();
        deliveryRecordDetailQueryWrapper.eq("delivery_record_id", detailBy.getId());
        deliveryRecordDetailQueryWrapper.eq("is_deleted", false);
        List<DeliveryRecordDetail> list = deliveryRecordDetailService.list(deliveryRecordDetailQueryWrapper);
        detailBy.setDeliveryRecordDetails(list);
        list.stream().forEach(deliveryRecordDetail -> {
            deliveryRecordDetail.setMainUnitId(deliveryRecordDetail.getUnitId());
            deliveryRecordDetail.setMainUnitName(deliveryRecordDetail.getUnitName());
            deliveryRecordDetail.setSkuName(deliveryRecordDetail.getProductName());
            deliveryRecordDetail.setSkuSpec(deliveryRecordDetail.getSkuSpec());
            deliveryRecordDetail.setProductDetailId(deliveryRecordDetail.getSkuId());
            deliveryRecordDetail.setSelRemainQuality(deliveryRecordDetail.getSurplus());
            deliveryRecordDetail.setSubtotalAmount(deliveryRecordDetail.getSubtotalAmount());
            if (deliveryRecordDetail.getSubtotalAmount() != null) {
                if (deliveryRecordDetail.getShipmentQty() != null && deliveryRecordDetail.getShipmentQty() > 0) {
                    BigDecimal result = deliveryRecordDetail.getSubtotalAmount().divide(new BigDecimal(deliveryRecordDetail.getShipmentQty()));
                    deliveryRecordDetail.setCurrentCostPrice(result);
                }
            }
            if (StringUtils.isNotBlank(deliveryRecordDetail.getDeliverySituation())) {
                deliveryRecordDetail.setDeliverySituationName(ProductEnum.deliverySituationEmum.getNameByCode(deliveryRecordDetail.getDeliverySituation()));
            }
        });
        return detailBy;
    }
}
